package com.work.utils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @program: transfer
 * @description
 * @author: luffy
 * @create: 2020-07-01 09:29
 */
public class ConnectionUtils {
    /**
     * 利用饿汉式单例模式保证获取的ConnectionUtils是同一个
     */
//    private ConnectionUtils() {
//    }

    private static ConnectionUtils connectionUtils = new ConnectionUtils();
    public static ConnectionUtils getInstance() {
        return connectionUtils;
    }


    private ThreadLocal<Connection> threadConnection = new ThreadLocal<>();
    /**
     * 从当前线程获取连接
     */
    public Connection getConnection(){
        /**
         * 判断当前线程是否绑定连接，没有绑定就从连接池中获取一个链接
         */
        Connection connection = threadConnection.get();
        if (connection == null) {
            try {
                 connection = DruidUtils.getInstance().getConnection();
                threadConnection.set(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;

    }
}
